<template>
  <div class="JNPF-common-layout">
    <div class="JNPF-common-layout-center">
      <el-row class="JNPF-common-search-box" :gutter="16">
        <el-form @submit.native.prevent label-width="80px" label-position="left">
          <el-col :span="6">
            <el-form-item label="角色名称">
      <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;" placeholder="请输入角色名称"/>
      </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="handleFilter">查找</el-button>
              <el-button type="success" @click="handleCreate">添加</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="JNPF-common-layout-main JNPF-flex-main">
       <!-- 查询结果 -->
    <JNPF-table stripe :height="buttonColor.clientHeight" v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row :header-cell-style="tableColor">
       <el-table-column :width="buttonColor.operationThree" align="center" label="操作" width="130">
        <template slot-scope="scope">
          <el-button type="text" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
          <el-button type="text" @click="handlePermission(scope.row)">授权</el-button>
        </template>
      </el-table-column>
      <el-table-column :index="indexMethod" :width="buttonColor.line" align="center" label="序号" type="index" sortable/>
      <el-table-column width="80" align="left" label="角色编号" prop="id"/>
      <el-table-column align="left" label="角色名称" prop="name" sortable/>
      <el-table-column align="left" label="说明" prop="description"/>
    </JNPF-table>
    <paginations
	:total="total"
	:page.sync="listQuery.currentPage"
	:limit.sync="listQuery.pageSize"
	/>
      </div>
    </div>
    <!-- 添加或修改对话框 -->
    <el-dialog :close-on-click-modal="false" :visible.sync="dialogFormVisible" width="40%" :title="textMap[dialogStatus]">
      <el-row class="JNPF-common-search-box" :gutter="16">
        <el-form @submit.native.prevent label-width="80px" label-position="left" ref="dataForm" :rules="rules" :model="dataForm">
          <el-col :span="24">
            <el-form-item   label="角色名称" prop="name">
              <el-input v-model="dataForm.name"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item  label="说明" prop="desc">
              <el-input v-model="dataForm.description"/>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" v-if="dialogStatus=='create'" @click="createData">确定</el-button>
        <el-button type="primary" v-else @click="updateData">确定</el-button>
      </span>
    </el-dialog>
    <!-- 权限配置对话框 -->
    <el-dialog width="50%" top="10px" :title="'角色权限'+rolename" class="roleWidth" :close-on-click-modal="false" :visible.sync="permissionDialogFormVisible">
      <el-tree
      style="height:400px !important;overflow:auto !important;padding: 0 20px !important"
        ref="tree"
        :data="systemPermissions"
        :default-checked-keys="assignedPermissions"
        show-checkbox
        node-key="id"
        highlight-current>
      </el-tree>
      <span slot="footer" class="dialog-footer" >
        <el-button type="info"  @click="permissionDialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updatePermission">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { listRole, createRole, updateRole, deleteRole, getPermissions, updatePermission } from '@/api/role'
import Pagination from '@/components/Pagination'
import { tableColor,titleColor,buttonColor } from '@/filters/index'

export default {
  name: 'Role',
  components: { Pagination },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined,
        sort: 'create_time',
        order: 'desc'
      },
      dataForm: {
        id: undefined,
        name: undefined,
        description: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      tableColor: tableColor,
      titleColor: titleColor,
      buttonColor:buttonColor,
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ]
      },
      permissionDialogFormVisible: false,
      systemPermissions: null,
      assignedPermissions: null,
      rolename: null,
      permissionForm: {
        roleId: undefined,
        permIds: []
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      listRole(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        name: undefined,
        description: undefined
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createRole(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加角色成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.msg
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateRole(this.dataForm, this.$route.query.id)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新角色成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.msg
              })
            })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('是否要删除该角色', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRole(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除角色成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.msg
            })
          })
      })
    },
    handlePermission(row) {
      this.permissionDialogFormVisible = true
      this.permissionForm.roleId = row.id
      this.rolename = row.name
      getPermissions(row.id)
        .then(response => {
          this.systemPermissions = response.data.data.all
          console.log(this.systemPermissions)
          this.assignedPermissions = response.data.data.assigned
        })
    },
    updatePermission() {
      this.permissionForm.permIds = this.$refs.tree.getCheckedKeys(false).concat(this.$refs.tree.getHalfCheckedKeys())
      updatePermission(this.permissionForm)
        .then(response => {
          this.permissionDialogFormVisible = false
          this.$notify.success({
            title: '成功',
            message: '授权成功'
          })
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.msg
          })
        })
    },
    indexMethod(index) {
      index = index + 1
      return index
    }
  }
}
</script>